import React from "react";
import BaseComp from "../Base/BaseComp";
import BraftEditor from "braft-editor";
import  { ContentUtils }   from "braft-utils";
import "braft-editor/dist/index.css";
import styles from "./index.module.less";
import { Upload, Button, message } from "antd";
import { PictureOutlined } from "@ant-design/icons";
import {isObject, pick} from "lodash-es";
import { uploadDocApi } from "../../services/uploadApi";
import BaseField from "../Base/BaseField";
import BaseFormItem from "../Base/BaseFormItem";
import {isNotEmpty, isObjectValEqual} from "jh-utils";


/**
 * 富文本编辑器
 * @Author: Admin
 * @Date: 2021/2/23 10:28
 */
export class BraftEditorBase extends BaseField {



    static getDerivedStateFromProps(nextProps , preState ) {
        // console.log(!isObjectValEqual({defaultValue: nextProps.defaultValue}, {defaultValue: preState.defaultValue}));
        // 有 value，说明这是个受控组件，则以 value 为准
        if ('value' in nextProps && !isObjectValEqual({originValue: nextProps.value}, {originValue: preState.originValue})) {
            console.log('sValue',nextProps.value, preState.value,preState.originValue);
            return {
                tmpVal: BraftEditor.createEditorState(nextProps.value || ""),
                value: isNotEmpty(nextProps.value) ? nextProps.value : null,
                originValue: nextProps.value
            };

        } else if ('defaultValue' in nextProps && preState &&
            !isObjectValEqual({defaultValue: nextProps.defaultValue}, {defaultValue: preState.defaultValue})) {

            // 如果是作为非受控组件。当 defaultValue 改变，则更新组件内的数据
            return {
                tmpVal: BraftEditor.createEditorState(nextProps.defaultValue || ""),
                value: isNotEmpty(nextProps.defaultValue) ? nextProps.defaultValue : null,
                originValue: nextProps.defaultValue,
                defaultValue: nextProps.defaultValue
            };
        }
        return null;
    }

    initState(props) {
        let tmpVal = props.value || props.defaultValue || null;
        return {
            tmpVal:BraftEditor.createEditorState(tmpVal || ""),
            value: props.value || props.defaultValue || null,
            defaultValue: props.defaultValue,
            originValue: props.value
        }
    }

    onChange(value){
        // console.log('value', value)
        this.setState({tmpVal: value});
    }

    onBlur(e){
        this.hdlValueChange(this.state.tmpVal && this.state.tmpVal.toHTML ? this.state.tmpVal.toHTML():'');
    }

    /**
     *  上传回调
     * @param info
     * @returns {boolean}
     */
    uploadChange(info){
        // console.log('info',info);
        if(!info || (info && !info.file)) return false;

        if(info.file.status === "done") {
            const { response } = info.file;
            if (response) {
                let res = isObject(response) ? { ...response } : {};
                if (res.status == 200 && res.data) {
                    this.onChange(ContentUtils.insertHTML(this.state.tmpVal,`<p><img src="${res.data.path}" data-src="${res.data.path}"/></p>`));
                }
            }
        }else if(info.file.status === "error") {
            message.error(this.formatMsgByCn('操作失败'))
        }

    }

    /**
     * 判断是否拖拽中
     * @type {boolean}
     */
    drag = false;
    /**
     * 拖拽起始位置
     * @type {number}
     */
    oldXY = 0;

    handleStart(event){
        this.drag = true;
        this.oldXY = event.pageY;
        let content = document.getElementsByClassName('bf-content');
        content = content && content[0];
        if(content){
            let midHeight = content.clientHeight;
            document.onmousemove = e => {
                // console.log('e:',e,content)
                if (this.drag) {
                    let y = e.pageY - this.oldXY + midHeight;
                    content.style.height = `${y}px`
                }
            };
            document.onmouseup = () => {
                this.oldXY = 0;
                if (this.drag) {
                    this.drag = false;
                }
            };
        }

    }

    mainRender(context) {
        let { className, style = {}, controls, extendControls, isDrag } = this.props;
        let {tmpVal } = this.state;
        controls = controls ? controls : [
            "undo","redo", "separator", "font-size", "line-height", "letter-spacing", "text-color",
            "bold", "italic", "underline", "strike-through", "separator", "superscript", "subscript",
            "remove-styles", "emoji", "text-indent", "text-align", "headings", "list-ul", "list-ol",
            "blockquote", "code", "link", "hr", "clear", "fullscreen"
        ];
        extendControls = extendControls ? extendControls : [
            {
                key: 'antd-uploader',
                type: "component",
                component: (
                    <Upload
                        name={'file'}
                        action={uploadDocApi.api}
                        showUploadList={false}
                        onChange={this.uploadChange.bind(this)}
                    >
                        <Button className={"control-item button upload-button"} data-title={"插入图片"}>
                            <PictureOutlined/>
                        </Button>
                    </Upload>
                )
            }
        ];

        let width = style.width || "100%";
        let height = style.height || "100%";

        return  <div className={styles.mainEditor}>
            <BraftEditor
                ref={ref => {
                    setTimeout(()=>{
                        let controlbar = document.querySelector('.braftContainer .bf-controlbar');
                        let content = document.querySelector('.braftContainer .bf-content');
                        if(!isDrag && controlbar && content && content.style){
                            let height = `calc(100% - ${controlbar.offsetHeight}px)`;
                            content.style.height = height;
                        }
                    });

                }}
                value={tmpVal || ''}
                onChange={this.onChange.bind(this)}
                onBlur={this.onBlur.bind(this)}
                extendControls={extendControls}
                controls={controls}
                className={className ? className : `braftContainer`}
                style={{width, height}}
            />
            {
                isDrag === true && !style.height && <div className={styles['box-drag-handle-s']}
                                                         onMouseDown={e => this.handleStart(e)}
                />
            }
        </div>
    }
}

export default class BraftEditorComp extends BaseFormItem {
    Comp = BraftEditorBase
}
